02. Geolocation

Geolocation

Introduction to Geolocation

A common feature of native applications is the ability to access and receive updates about the user's current location. Like most things, Expo makes this rather straightforward by giving us a JavaScript API that will work on both iOS and Android.

import { Location } from 'expo';

Typically when dealing with location services, there are one of two features you'll need: getting the user's current location, or getting and watching the user's current location for updates. Expo's Location property gives us both of these options with getCurrentPositionAsync and watchPositionAsync.

getCurrentPositionAsync gets the current location of the device, without watching for future updates. watchPositionAsync will also get the current location of the device, but it will also subscribe to location updates. This way, you'll be notified if that device moves location.

For the full documentation on how to use Expo's Location property, visit Location

💡 Geolocation Tips 💡

Whenever you're dealing with a feature that requires the user's permission to work properly, it's important that you account for all the different UI options that could be shown. For example, when dealing with a user's location, there are three scenarios to manage:

  1. The user gives you permission to view their location (best-case scenario).
  2. The user decides to neither deny nor grant you permission to their location.
  3. The user denies giving you access to their location.

In an ideal world, the user would always grant you permission to whatever you'd like, but, this isn't always the case and as a UI developer, you need to plan accordingly for those moments.

Live-Undetermined

Live-Denied

Live-Granted

Live-SetLocation

Here's the commit with the changes made in this video.

Be sure that you have included the following imports: in Live.js:

import { Location, Permissions } from 'expo';
import { calculateDirection } from '../utils/helpers';

Live-AskPermission

Here's the commit with the changes made in this video.

Note: If you are running into errors with the code in this commit, update the initial value of the Live's state's coords property to a non-null value.

Which of the following methods would you use to subscribe to the user's location using Expo? Select all that apply.

SOLUTION:
  • `watchPositionAsync`

Task Description:

As we wrap up adding geolocation to the application, how are things looking on your end?

Task List:

Task Feedback:

Fantastic!

Summary

In this concept, we saw how to use Expo's Location property to watch the user's current location using watchPositionAsync. For further reading, feel free to check out the official documentation.